package com.letv.core.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;

import com.letv.core.bean.AlbumNew;
import com.letv.core.bean.PlayRecord;
import com.letv.core.bean.PlayRecordList;
import com.letv.core.constant.DatabaseConstant;
import com.letv.core.utils.LogInfo;

public class PlayRecordHandler {
    private static final String TAG = PlayRecordHandler.class.getSimpleName();

    private Context context;

    public PlayRecordHandler(Context context) {
        this.context = context;
    }

    /**
     * 上传成功后，将状态切换成正常
     * */
    public synchronized void save2Normal(int pid, int vid) {
        ContentValues cv = new ContentValues();
        cv.put(DatabaseConstant.PlayRecord.Field.STATE, 0);
        context.getContentResolver().update(LetvContentProvider.URI_PLAYTRACE, cv,
                pid <= 0 ? DatabaseConstant.PlayRecord.Field.VID + "=?" : DatabaseConstant.PlayRecord.Field.PID + "=?",
                pid <= 0 ? new String[] { vid + "" } : new String[] { pid + "" });
    }

    /**
     * 来自于网络保存播放记录
     * */
    public synchronized void savePlayTraceFromWeb(int cid, int pid, int vid, int nvid, String uid, int from, int vtype,
            long vtime, long htime, long utime, String title, String img, int state, float nc, String img300,
            String videoTypeKey) {
        LogInfo.log("Emerson", "------来自网络 videoTypeKey = " + videoTypeKey);
        if (pid <= 0) {
          //pid <=0 不是专辑
            PlayRecord playRecord = getPlayTraceByEpsodeId(vid);
            if (playRecord != null) {
                if (playRecord.getVideoId() == vid && !TextUtils.isEmpty(playRecord.getImg300())) {// 判断，原纪录和新纪录是一个视频，并且有300的图，就不替换了
                    updateByVidFromWeb(vid, nvid, from, htime, utime, title, img, state, playRecord.getImg300(),videoTypeKey);
                } else {
                    updateByVidFromWeb(vid, nvid, from, htime, utime, title, img, state, img300, videoTypeKey);
                }
            } else {

                int type = 0;
                if (pid <= 0) {
                    type = AlbumNew.Type.VRS_ONE;
                } else {
                    if (pid == vid) {
                        type = AlbumNew.Type.VRS_ONE;
                    } else {
                        type = AlbumNew.Type.VRS_MANG;
                    }
                }

                ContentValues cv = new ContentValues();

                cv.put(DatabaseConstant.PlayRecord.Field.CID, cid);
                cv.put(DatabaseConstant.PlayRecord.Field.PID, pid <= 0 ? vid : pid);
                cv.put(DatabaseConstant.PlayRecord.Field.VID, vid);
                cv.put(DatabaseConstant.PlayRecord.Field.NVID, nvid);
                cv.put(DatabaseConstant.PlayRecord.Field.UID, uid);
                cv.put(DatabaseConstant.PlayRecord.Field.FROM, from);
                cv.put(DatabaseConstant.PlayRecord.Field.VTYPE, vtype);
                cv.put(DatabaseConstant.PlayRecord.Field.VTIME, vtime);
                cv.put(DatabaseConstant.PlayRecord.Field.HTIME, htime);
                cv.put(DatabaseConstant.PlayRecord.Field.UTIME, utime);
                cv.put(DatabaseConstant.PlayRecord.Field.TITLE, title);
                cv.put(DatabaseConstant.PlayRecord.Field.IMG, img);
                cv.put(DatabaseConstant.PlayRecord.Field.IMG300, img300);
                cv.put(DatabaseConstant.PlayRecord.Field.STATE, state);
                cv.put(DatabaseConstant.PlayRecord.Field.NC, nc + "");
                cv.put(DatabaseConstant.PlayRecord.Field.TYPE, type);
                cv.put(DatabaseConstant.PlayRecord.Field.VIDEOTYPEKEY, videoTypeKey);

                context.getContentResolver().insert(LetvContentProvider.URI_PLAYTRACE, cv);
            }
        } else {
            //pid >0逻辑 是专辑
            PlayRecord playRecord = getPlayTraceByAlbumId(pid);
            if (playRecord != null) {
                if (playRecord.getVideoId() == vid && !TextUtils.isEmpty(playRecord.getImg300())) {// 判断，原纪录和新纪录是一个视频，并且有300的图，就不替换了
                    img300 = playRecord.getImg300();
                }
                if (TextUtils.isEmpty(videoTypeKey)) {
                    videoTypeKey = playRecord.getvideoTypeKey();
                }
                updateByPid(pid, vid, nvid, from, htime, utime, title, img, state, img300, videoTypeKey);
            } else {
                int type = 0;
                if (pid == vid) {
                    type = AlbumNew.Type.VRS_ONE;
                } else {
                    type = AlbumNew.Type.VRS_MANG;
                }
                ContentValues cv = new ContentValues();

                cv.put(DatabaseConstant.PlayRecord.Field.CID, cid);
                cv.put(DatabaseConstant.PlayRecord.Field.PID, pid < 0 ? vid : pid);
                cv.put(DatabaseConstant.PlayRecord.Field.VID, vid);
                cv.put(DatabaseConstant.PlayRecord.Field.NVID, nvid);
                cv.put(DatabaseConstant.PlayRecord.Field.UID, uid);
                cv.put(DatabaseConstant.PlayRecord.Field.FROM, from);
                cv.put(DatabaseConstant.PlayRecord.Field.VTYPE, vtype);
                cv.put(DatabaseConstant.PlayRecord.Field.VTIME, vtime);
                cv.put(DatabaseConstant.PlayRecord.Field.HTIME, htime);
                cv.put(DatabaseConstant.PlayRecord.Field.UTIME, utime);
                cv.put(DatabaseConstant.PlayRecord.Field.TITLE, title);
                cv.put(DatabaseConstant.PlayRecord.Field.IMG, img);
                cv.put(DatabaseConstant.PlayRecord.Field.IMG300, img300);
                cv.put(DatabaseConstant.PlayRecord.Field.NC, nc);
                cv.put(DatabaseConstant.PlayRecord.Field.STATE, state);
                cv.put(DatabaseConstant.PlayRecord.Field.TYPE, type);
                cv.put(DatabaseConstant.PlayRecord.Field.VIDEOTYPEKEY, videoTypeKey);

                context.getContentResolver().insert(LetvContentProvider.URI_PLAYTRACE, cv);
            }
        }
    }

    /**
     * 保存播放记录
     * */
    public synchronized void savePlayTrace(int cid, int pid, int vid, int nvid, String uid, int from, int vtype,
            long vtime, long htime, long utime, String title, String img, int state, float nc, String img300,
            String videoTypeKey) {
        if (pid <= 0) {
            PlayRecord playRecord = getPlayTraceByEpsodeId(vid);
            if (playRecord != null) {
                if (playRecord.getVideoId() == vid && !TextUtils.isEmpty(playRecord.getImg300())) {// 判断，原纪录和新纪录是一个视频，并且有300的图，就不替换了
                    updateByVid(vid, nvid, from, htime, utime, title, img, state, playRecord.getImg300(), videoTypeKey);
                } else {
                    updateByVid(vid, nvid, from, htime, utime, title, img, state, img300, videoTypeKey);
                }
            } else {

                int type = 0;
                if (pid <= 0) {
                    type = AlbumNew.Type.VRS_ONE;
                } else {
                    if (pid == vid) {
                        type = AlbumNew.Type.VRS_ONE;
                    } else {
                        type = AlbumNew.Type.VRS_MANG;
                    }
                }

                ContentValues cv = new ContentValues();

                cv.put(DatabaseConstant.PlayRecord.Field.CID, cid);
                cv.put(DatabaseConstant.PlayRecord.Field.PID, pid <= 0 ? vid : pid);
                cv.put(DatabaseConstant.PlayRecord.Field.VID, vid);
                cv.put(DatabaseConstant.PlayRecord.Field.NVID, nvid);
                cv.put(DatabaseConstant.PlayRecord.Field.UID, uid);
                cv.put(DatabaseConstant.PlayRecord.Field.FROM, from);
                cv.put(DatabaseConstant.PlayRecord.Field.VTYPE, vtype);
                cv.put(DatabaseConstant.PlayRecord.Field.VTIME, vtime);
                cv.put(DatabaseConstant.PlayRecord.Field.HTIME, htime);
                cv.put(DatabaseConstant.PlayRecord.Field.UTIME, utime);
                cv.put(DatabaseConstant.PlayRecord.Field.TITLE, title);
                cv.put(DatabaseConstant.PlayRecord.Field.IMG, img);
                cv.put(DatabaseConstant.PlayRecord.Field.IMG300, img300);
                cv.put(DatabaseConstant.PlayRecord.Field.STATE, state);
                cv.put(DatabaseConstant.PlayRecord.Field.NC, nc + "");
                cv.put(DatabaseConstant.PlayRecord.Field.TYPE, type);
                cv.put(DatabaseConstant.PlayRecord.Field.VIDEOTYPEKEY, videoTypeKey);

                context.getContentResolver().insert(LetvContentProvider.URI_PLAYTRACE, cv);
            }
        } else {
            PlayRecord playRecord = getPlayTraceByAlbumId(pid);
            if (playRecord != null) {
                if (playRecord.getVideoId() == vid && !TextUtils.isEmpty(playRecord.getImg300())) {// 判断，原纪录和新纪录是一个视频，并且有300的图，就不替换了
                    img300 = playRecord.getImg300();
                }
                updateByPid(pid, vid, nvid, from, htime, utime, title, img, state, img300, videoTypeKey);
            } else {

                int type = 0;
                if (pid <= 0) {
                    type = AlbumNew.Type.VRS_ONE;
                } else {
                    if (pid == vid) {
                        type = AlbumNew.Type.VRS_ONE;
                    } else {
                        type = AlbumNew.Type.VRS_MANG;
                    }
                }

                ContentValues cv = new ContentValues();

                cv.put(DatabaseConstant.PlayRecord.Field.CID, cid);
                cv.put(DatabaseConstant.PlayRecord.Field.PID, pid < 0 ? vid : pid);
                cv.put(DatabaseConstant.PlayRecord.Field.VID, vid);
                cv.put(DatabaseConstant.PlayRecord.Field.NVID, nvid);
                cv.put(DatabaseConstant.PlayRecord.Field.UID, uid);
                cv.put(DatabaseConstant.PlayRecord.Field.FROM, from);
                cv.put(DatabaseConstant.PlayRecord.Field.VTYPE, vtype);
                cv.put(DatabaseConstant.PlayRecord.Field.VTIME, vtime);
                cv.put(DatabaseConstant.PlayRecord.Field.HTIME, htime);
                cv.put(DatabaseConstant.PlayRecord.Field.UTIME, utime);
                cv.put(DatabaseConstant.PlayRecord.Field.TITLE, title);
                cv.put(DatabaseConstant.PlayRecord.Field.IMG, img);
                cv.put(DatabaseConstant.PlayRecord.Field.IMG300, img300);
                cv.put(DatabaseConstant.PlayRecord.Field.NC, nc);
                cv.put(DatabaseConstant.PlayRecord.Field.STATE, state);
                cv.put(DatabaseConstant.PlayRecord.Field.TYPE, type);
                cv.put(DatabaseConstant.PlayRecord.Field.VIDEOTYPEKEY, videoTypeKey);

                context.getContentResolver().insert(LetvContentProvider.URI_PLAYTRACE, cv);
            }
        }
    }

    /**
     * 通过VID或PID得到详情
     * */
    public synchronized PlayRecord getPlayTrace(int id) {
        Cursor cursor = null;
        PlayRecord mPlayRecord = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE, null,
                    DatabaseConstant.PlayRecord.Field.PID + "= ? OR " + DatabaseConstant.PlayRecord.Field.VID + "= ?",
                    new String[] { id + "", id + "" }, null);

            if (cursor != null && cursor.moveToNext()) {
                mPlayRecord = createPlayRecord(cursor);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeCursor(cursor);
        }

        return mPlayRecord;
    }

    /**
     * 关闭数据库Cursor对象
     */
    public static void closeCursor(Cursor cursor) {
        if (null != cursor) {
            if (!cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    /**
     * 通过专辑ID得到播放记录
     * */
    public synchronized PlayRecord getPlayTraceByAlbumId(int pid) {
        Cursor cursor = null;
        PlayRecord mPlayTrace = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE, null,
                    DatabaseConstant.PlayRecord.Field.PID + "= ?", new String[] { pid + "" }, null);

            if (cursor != null && cursor.moveToNext()) {

                mPlayTrace = createPlayRecord(cursor);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            closeCursor(cursor);
        }

        return mPlayTrace;
    }

    /**
     * 通过视频ID得到播放记录
     * */
    public synchronized PlayRecord getPlayTraceByEpsodeId(int vid) {
        Cursor cursor = null;
        PlayRecord mPlayRecord = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE, null,
                    DatabaseConstant.PlayRecord.Field.VID + "= ?", new String[] { vid + "" }, null);

            if (cursor != null && cursor.moveToNext()) {
                mPlayRecord = createPlayRecord(cursor);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeCursor(cursor);
        }

        return mPlayRecord;
    }

    /**
     * 通过vid获取指定该视频所在的Pid, added by chenhong, 2015-05-03
     * */
    public long queryPlayTracePidByWatchedStatus(long vid) {
        Cursor cursor = null;
        long retPid = 0L;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE_WATCHED,
                    new String[] { "vid" }, DatabaseConstant.PlayRecordWatched.Field.VID + "= ?",
                    new String[] { vid + "" }, null);

            if (cursor != null && cursor.moveToNext()) {
                retPid = cursor.getLong(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.PID));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeCursor(cursor);
        }
        return retPid;
    }

    /**
     * 通过pid, vid获取指定集数的视频是否已播放, added by chenhong, 2015-01-26
     * */
    public boolean queryPlayTraceByWatchedStatus(long vid) {
        Cursor cursor = null;
        boolean bFlag = false;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE_WATCHED, null,
                    DatabaseConstant.PlayRecordWatched.Field.VID + "= ?", new String[] { vid + "" }, null);
            if (cursor != null && cursor.moveToNext()) {
                bFlag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeCursor(cursor);
        }
        return bFlag;
    }

    /**
     * 插入指定集数的视频是否已播放, added by chenhong, 2015-01-26
     * */
    public synchronized void insertPlayTraceByWatchedStatus(long pid, long vid) {
        if (pid <= 0 || vid <= 0 ) {
            LogInfo.log(TAG, "error! pid and vid must > 0");
            return;
        }

        /*
         * 当已观看记录>10000记录时，删除100行
         */
        Log.d("hong2", "##############insertPlayTraceByWatchedStatus############## pid:" + pid + " vid:" + vid);
        if (queryPlayTraceByWatchedStatusTotalNum()) {
            deletePlayTraceByWatchedStatusSurplus();
        }

        if (!queryPlayTraceByWatchedStatus(vid)) {
            ContentValues cv = new ContentValues();
            cv.put(DatabaseConstant.PlayRecordWatched.Field.PID, pid <= 0 ? vid : pid);
            cv.put(DatabaseConstant.PlayRecordWatched.Field.VID, vid);
            context.getContentResolver().insert(LetvContentProvider.URI_PLAYTRACE_WATCHED, cv);
        }
    }

    /**
     * 删除指定已播放的集数, added by chenhong, 2015-01-26
     * */
    public synchronized void deletePlayTraceByWatchedStatus(long pid) {
        context.getContentResolver().delete(LetvContentProvider.URI_PLAYTRACE_WATCHED,
                DatabaseConstant.PlayRecordWatched.Field.PID + "= ?", new String[] { pid + "" });
    }

    /**
     * 删除指定已播放的集数, added by chenhong, 2015-01-26
     * */
    public synchronized void deletePlayTraceByWatchedStatusByVid(long vid) {
        context.getContentResolver().delete(LetvContentProvider.URI_PLAYTRACE_WATCHED,
                DatabaseConstant.PlayRecordWatched.Field.VID + "= ?", new String[] { vid + "" });
    }

    /*
     * 查询当前所有的已观看播放数
     */
    public synchronized boolean queryPlayTraceByWatchedStatusTotalNum() {
        Cursor cursor = null;
        boolean bFlag = false;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE_WATCHED,
                    new String[] { "vid" }, null, null, null);

            if (cursor != null && cursor.moveToNext()) {
                int totalNum = cursor.getCount();
                if (totalNum >= 10000) { // 10
                    bFlag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("hong2", "queryPlayTraceByWatchedStatus exception");
        } finally {
            closeCursor(cursor);
        }
        return bFlag;
    }

    /*
     * 删除100行已观看的播放记录
     */
    public void deletePlayTraceByWatchedStatusSurplus() {
        int deleteNum = context.getContentResolver().delete(LetvContentProvider.URI_PLAYTRACE_WATCHED,
                "vid in (select vid from playtablewatched limit 100)", null);
        Log.d("hong", "deletePlayTraceByWatchedStatusSurplus delete number " + deleteNum);
    }

    /**
     * 得到所有的播放记录
     * */
    public synchronized PlayRecordList getAllPlayTrace() {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE, null,
                    DatabaseConstant.PlayRecord.Field.STATE + "<> ?", new String[] { "2" },
                    DatabaseConstant.PlayRecord.Field.UTIME + " desc");
            PlayRecordList list = new PlayRecordList();
            while (cursor != null && cursor.moveToNext()) {
                list.add(createPlayRecord(cursor));
            }

            return list;
        } finally {
            closeCursor(cursor);
        }
    }

    /**
     * 得到最近一条记录
     * */
    public synchronized PlayRecord getLastPlayTrace() {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE, null,
                    DatabaseConstant.PlayRecord.Field.STATE + "<> ?", new String[] { "2" },
                    DatabaseConstant.PlayRecord.Field.UTIME + " desc");
            if (cursor.moveToNext()) {
                return createPlayRecord(cursor);
            }

            return null;
        } finally {
            closeCursor(cursor);
        }
    }

    /**
     * 得到最新的n条记录
     * */
    public synchronized PlayRecordList getLastPlayTrace(int num) {
        Cursor cursor = null;
        try {
            PlayRecordList list = new PlayRecordList();
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE, null,
                    DatabaseConstant.PlayRecord.Field.STATE + "<> ?", new String[] { "2" },
                    DatabaseConstant.PlayRecord.Field.UTIME + " desc");
            while (cursor != null && cursor.moveToNext() && num > 0) {
                list.add(createPlayRecord(cursor));
                num--;
            }
            return list;
        } finally {
            closeCursor(cursor);
        }
    }

    /**
     * 清除所有播放记录
     * */
    public synchronized void clearAll() {
        context.getContentResolver().delete(LetvContentProvider.URI_PLAYTRACE, null, null);
    }

    /**
     * 标记清除所有播放记录，等待上传
     * */
    public synchronized void tagClearAll() {
        ContentValues cv = new ContentValues();

        cv.put(DatabaseConstant.PlayRecord.Field.UTIME, System.currentTimeMillis() / 1000);
        cv.put(DatabaseConstant.PlayRecord.Field.STATE, "2");

        context.getContentResolver().update(LetvContentProvider.URI_PLAYTRACE, cv, null, null);
    }

    /**
     * 清除所有播放记录
     * */
    public synchronized void clearAllCloud() {
        context.getContentResolver().delete(LetvContentProvider.URI_PLAYTRACE,
                DatabaseConstant.PlayRecord.Field.STATE + "= ?", new String[] { "0" });
    }

    /**
     * 根据专辑ID删除专辑的播放记录
     */
    public synchronized void deleteByPid(int pid) {
        context.getContentResolver().delete(LetvContentProvider.URI_PLAYTRACE,
                DatabaseConstant.PlayRecord.Field.PID + "= ?", new String[] { pid + "" });
    }

    /**
     * 根据视频ID删除一条的播放记录
     */
    public synchronized void deleteByVid(int vid) {
        context.getContentResolver().delete(LetvContentProvider.URI_PLAYTRACE,
                DatabaseConstant.PlayRecord.Field.VID + "= ?", new String[] { vid + "", });
    }

    /**
     * 根据专辑ID删除专辑的播放记录
     */
    public synchronized void tagDeleteByPid(int pid) {
        ContentValues cv = new ContentValues();

        cv.put(DatabaseConstant.PlayRecord.Field.UTIME, System.currentTimeMillis() / 1000);
        cv.put(DatabaseConstant.PlayRecord.Field.STATE, "2");

        context.getContentResolver().update(LetvContentProvider.URI_PLAYTRACE, cv,
                DatabaseConstant.PlayRecord.Field.PID + "=?", new String[] { pid + "" });
    }

    /**
     * 根据视频ID删除一条的播放记录
     */
    public synchronized void tagDeleteByVid(int vid) {
        ContentValues cv = new ContentValues();

        cv.put(DatabaseConstant.PlayRecord.Field.UTIME, System.currentTimeMillis() / 1000);
        cv.put(DatabaseConstant.PlayRecord.Field.STATE, "2");

        context.getContentResolver().update(LetvContentProvider.URI_PLAYTRACE, cv,
                DatabaseConstant.PlayRecord.Field.VID + "=?", new String[] { vid + "" });
    }

    public synchronized PlayRecordList getTagDeletes() {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE, null,
                    DatabaseConstant.PlayRecord.Field.STATE + "== ?", new String[] { "2" }, null);
            PlayRecordList list = new PlayRecordList();
            while (cursor.moveToNext()) {
                list.add(createPlayRecord(cursor));
            }

            return list;
        } finally {
            closeCursor(cursor);
        }
    }

    public synchronized PlayRecordList getTagSubmits() {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE, null,
                    DatabaseConstant.PlayRecord.Field.STATE + "== ?", new String[] { "1" }, null);
            PlayRecordList list = new PlayRecordList();
            while (cursor.moveToNext()) {
                list.add(createPlayRecord(cursor));
            }

            return list;
        } finally {
            closeCursor(cursor);
        }
    }

    /**
     * 查询播放记录是否存在
     */
    public synchronized long getPlayPostion(int vid) {
        Cursor cursor = null;
        try {
            long position = 0;

            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE,
                    new String[] { DatabaseConstant.PlayRecord.Field.HTIME },
                    DatabaseConstant.PlayRecord.Field.VID + "= ?", new String[] { vid + "" }, null);

            if (cursor.moveToNext()) {
                position = cursor.getLong(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.HTIME));
            }
            return position;
        } finally {
            closeCursor(cursor);
        }
    }

    public synchronized boolean hasByPid(int pid) {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE,
                    new String[] { DatabaseConstant.PlayRecord.Field.VID },
                    DatabaseConstant.PlayRecord.Field.PID + "= ?", new String[] { pid + "" }, null);
            return cursor.getCount() > 0;
        } finally {
            closeCursor(cursor);
        }
    }

    public synchronized boolean hasByVid(int vid) {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(LetvContentProvider.URI_PLAYTRACE,
                    new String[] { DatabaseConstant.PlayRecord.Field.VID },
                    DatabaseConstant.PlayRecord.Field.VID + "= ?", new String[] { vid + "" }, null);
            return cursor.getCount() > 0;
        } finally {
            closeCursor(cursor);
        }
    }

    /**
     * 通过专辑ID更新播放记录，存在专辑ID的情况
     * */
    public synchronized void updateByPid(int pid, int vid, int nvid, int from, long htime, long utime, String title,
            String img, int state, String img300, String videoTypeKey) {
        ContentValues cv = new ContentValues();

        cv.put(DatabaseConstant.PlayRecord.Field.PID, pid);
        cv.put(DatabaseConstant.PlayRecord.Field.VID, vid);
        cv.put(DatabaseConstant.PlayRecord.Field.NVID, nvid);
        cv.put(DatabaseConstant.PlayRecord.Field.FROM, from);
        cv.put(DatabaseConstant.PlayRecord.Field.HTIME, htime);
        cv.put(DatabaseConstant.PlayRecord.Field.UTIME, utime);
        cv.put(DatabaseConstant.PlayRecord.Field.TITLE, title);
        cv.put(DatabaseConstant.PlayRecord.Field.IMG, img);
        cv.put(DatabaseConstant.PlayRecord.Field.IMG300, img300);
        cv.put(DatabaseConstant.PlayRecord.Field.STATE, state);
        cv.put(DatabaseConstant.PlayRecord.Field.VIDEOTYPEKEY, videoTypeKey);

        int i = context.getContentResolver().update(LetvContentProvider.URI_PLAYTRACE, cv,
                DatabaseConstant.PlayRecord.Field.PID + "=? AND " + DatabaseConstant.PlayRecord.Field.UTIME + " <=?",
                new String[] { pid + "", utime + "" });
    }

    /**
     * 通过视频ID更新播放记录，不存在专辑ID的情况
     * */
    public synchronized void updateByVid(int vid, int nvid, int from, long htime, long utime, String title, String img,
            int state, String img300, String videoTypeKey) {

        ContentValues cv = new ContentValues();

        cv.put(DatabaseConstant.PlayRecord.Field.VID, vid);
        cv.put(DatabaseConstant.PlayRecord.Field.NVID, nvid);
        cv.put(DatabaseConstant.PlayRecord.Field.FROM, from);
        cv.put(DatabaseConstant.PlayRecord.Field.HTIME, htime);
        cv.put(DatabaseConstant.PlayRecord.Field.UTIME, utime);
        cv.put(DatabaseConstant.PlayRecord.Field.TITLE, title);
        cv.put(DatabaseConstant.PlayRecord.Field.IMG, img);
        cv.put(DatabaseConstant.PlayRecord.Field.IMG300, img300);
        cv.put(DatabaseConstant.PlayRecord.Field.STATE, state);
        cv.put(DatabaseConstant.PlayRecord.Field.VIDEOTYPEKEY, videoTypeKey);

        int i = context.getContentResolver().update(LetvContentProvider.URI_PLAYTRACE, cv,
                DatabaseConstant.PlayRecord.Field.VID + "=? AND " + DatabaseConstant.PlayRecord.Field.UTIME + " <=?",
                new String[] { vid + "", utime + "" });

    }

    /**
     * 通过视频ID更新播放记录，不存在专辑ID的情况
     * */
    public synchronized void updateByVidFromWeb(int vid, int nvid, int from, long htime, long utime, String title,
            String img, int state, String img300, String videoTypeKey) {
        PlayRecord playrecord = getPlayTrace(vid);
        if (playrecord != null && TextUtils.isEmpty(videoTypeKey)) {
            videoTypeKey = playrecord.getvideoTypeKey();
        }
        ContentValues cv = new ContentValues();

        cv.put(DatabaseConstant.PlayRecord.Field.VID, vid);
        cv.put(DatabaseConstant.PlayRecord.Field.NVID, nvid);
        cv.put(DatabaseConstant.PlayRecord.Field.FROM, from);
        cv.put(DatabaseConstant.PlayRecord.Field.HTIME, htime);
        cv.put(DatabaseConstant.PlayRecord.Field.UTIME, utime);
        cv.put(DatabaseConstant.PlayRecord.Field.TITLE, title);
        cv.put(DatabaseConstant.PlayRecord.Field.IMG, img);
        cv.put(DatabaseConstant.PlayRecord.Field.IMG300, img300);
        cv.put(DatabaseConstant.PlayRecord.Field.STATE, state);
        cv.put(DatabaseConstant.PlayRecord.Field.VIDEOTYPEKEY, videoTypeKey);

        int i = context.getContentResolver().update(LetvContentProvider.URI_PLAYTRACE, cv,
                DatabaseConstant.PlayRecord.Field.VID + "=? AND " + DatabaseConstant.PlayRecord.Field.UTIME + " <=?",
                new String[] { vid + "", utime + "" });

    }

    private PlayRecord createPlayRecord(Cursor cursor) {
        PlayRecord record = new PlayRecord();

        record.setChannelId(cursor.getInt(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.CID)));
        record.setAlbumId(cursor.getInt(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.PID)));
        record.setVideoId(cursor.getInt(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.VID)));
        record.setVideoNextId(cursor.getInt(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.NVID)));
        record.setUserId(cursor.getString(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.UID)));
        record.setFrom(cursor.getInt(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.FROM)));
        record.setVideoType(cursor.getInt(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.VTYPE)));
        record.setType(cursor.getInt(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.TYPE)));
        record.setTotalDuration(cursor.getLong(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.VTIME)));
        record.setPlayedDuration(cursor.getLong(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.HTIME)));
        record.setUpdateTime(cursor.getLong(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.UTIME)));
        record.setTitle(cursor.getString(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.TITLE)));
        record.setImg(cursor.getString(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.IMG)));
        record.setImg300(cursor.getString(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.IMG300)));
        record.setCurEpsoid(floatFormat(cursor.getString(cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.NC))));
        record.setvideoTypeKey(cursor.getString((cursor.getColumnIndex(DatabaseConstant.PlayRecord.Field.VIDEOTYPEKEY))));
        return record;
    }

    public static float floatFormat(String str) {
        float result = 0.0f;
        try {
            result = Float.parseFloat(str);
        } catch (Exception e) {
        }
        return result;
    }
}
